<template>
  <view>
    <view class="product-list">
      <view v-for="(product, i) in productList" :key="i" @click="showDetail(product)">
        <product-item :product="product"></product-item>
      </view>
    </view>
  </view>
</template>

<script>
  import{mapState} from 'vuex'
  export default {
    data() {
      return {
        //傳过來的类型參數对象
        typeObject: {
          //类型
          type:"",
          cid:"",
          pagenum:1,
          pagesize: 10
        },
        productList:[],
        alreadyGot:0,
        total:0,
        //節流閥
        isloading:false
       
      };
    },
    onLoad(options){
      this.typeObject.type = options.type || ''
      this.typeObject.cid = options.cid || ''
      //設置導航栏標題
      wx.setNavigationBarTitle({title:this.typeObject.type})
      this.getProductList()
    },
    methods:{
      async getProductList(cb){
        this.isloading = true//开節流閥
       const {data: res} = await uni.$http.get('/classify/type/'+this.typeObject.type +'/'+ this.typeObject.pagesize + '/' + this.alreadyGot)
       this.isloading = false//關節流閥
       cb && cb()
       if(res.meta.status != 200)return uni.$showMessage()
       //循环遍历將每一個產品的图片地址拼接
       res.list.forEach(x=>{return x.img_url = this.resourseUrl + x.img_url})
       this.productList = [...this.productList,...res.list]
       this.total = res.total
       if (this.alreadyGot < this.total){
         this.alreadyGot += this.typeObject.pagesize
       }else{
         this.alreadyGot = 0
       }
      },
      showDetail(product){
        uni.navigateTo({
          url: '/subpackage/product_detail/product_detail?product_id=' +product.product_id
        })
      }
    },
    //上拉加載更多商品
    onReachBottom(){
      if(this.isloading) return
      this.typeObject.pagenum++
      this.getProductList()
      
    },
    //下拉刷新數劇
    onPullDownRefresh(){
      this.typeObject.pagenum = 1
      this.total = 0
      this.isloading = false
      this.productList = []
      this.getProductList(() => uni.stopPullDownRefresh())
    },
    computed:{
      //映射resourseUrl过來
      ...mapState('user',['resourseUrl']),
    }
  }
</script>

<style lang="scss">
  

</style>
